package com.tjetc.service.Impl;

import com.tjetc.dao.CollectDishMapper;
import com.tjetc.dao.DishMapper;
import com.tjetc.dao.MerchantMapper;
import com.tjetc.entity.CollectDish;
import com.tjetc.entity.Dish;
import com.tjetc.entity.Merchant;
import com.tjetc.model.CollectDishDetail;
import com.tjetc.service.CollectDishService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class CollectDishServiceImpl implements CollectDishService {
    @Autowired
    private CollectDishMapper collectDishMapper;
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private MerchantMapper merchantMapper;

    /***
     * 添加菜品
     * @param collectDish
     * @return
     */
    @Override
    public int addDish(CollectDish collectDish) {
        CollectDish collectDish1 = collectDishMapper.selectCollectDish(collectDish.getUserId(), collectDish.getDishId());
        if(collectDish1!=null){
            return collectDish1.getId();
        }else{
            collectDishMapper.addDish(collectDish);
            return collectDish.getId();
        }

    }

    /***
     * 删除菜品
     * @param id
     * @return
     */
    @Override
    public int deleteDish(Integer id) {
        return collectDishMapper.deleteDish(id);
    }

    /***
     * 查询用户收藏菜品列表
     * @param userid
     * @return
     */
    @Override
    public List<CollectDishDetail> selectByUser(Integer userid) {
        List<CollectDish> collectDishes = collectDishMapper.selectByUser(userid);
        if(collectDishes==null){
            return new ArrayList<>();
        }
        //菜品id
        List<Integer> dishIds=new ArrayList<>();
        //要return的列表
        List<CollectDishDetail> dishes=new ArrayList<>();
        //获取菜品id列表
        for(int i=0;i<collectDishes.size();i++){
            dishIds.add(collectDishes.get(i).getDishId());
        }
        //查到的菜品信息的集合
        List<Dish> dishes1 = dishMapper.selectByList(dishIds);
        //设置信息
        for(int i=0;i<dishes1.size();i++){
            CollectDishDetail collectDishDetail=new CollectDishDetail();
            collectDishDetail.setDish(dishes1.get(i));
            Merchant merchant = merchantMapper.selectById(dishes1.get(i).getMerchantId());
            collectDishDetail.setShopName(merchant.getShopName());
            dishes.add(collectDishDetail);
        }
        return dishes;
    }

    /***
     * 判断该菜品是否被该用户收藏
     * @param userId
     * @param dishId
     * @return
     */
    @Override
    public CollectDish selectCollectDish(Integer userId, Integer dishId) {
        return collectDishMapper.selectCollectDish(userId, dishId);
    }
}
